package com.sso.oa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.HashSet;
import java.util.Set;

/**
 * OIDC 用户服务配置
 * 
 * @author SSO System
 * @since 2024-01-01
 */
@Configuration
public class OidcUserServiceConfig {

    /**
     * 自定义 OIDC 用户服务
     */
    @Bean
    public OidcUserService oidcUserService() {
        return new OidcUserService() {
            @Override
            public OidcUser loadUser(OidcUserRequest userRequest) {
                OidcUser oidcUser = super.loadUser(userRequest);
                
                // 获取用户信息
                OidcIdToken idToken = oidcUser.getIdToken();
                OidcUserInfo userInfo = oidcUser.getUserInfo();
                
                // 构建权限信息
                Set<SimpleGrantedAuthority> authorities = new HashSet<>();
                
                // 从idToken或userInfo中获取权限信息
                if (userInfo != null && userInfo.getClaim("authorities") != null) {
                    Object authoritiesClaim = userInfo.getClaim("authorities");
                    if (authoritiesClaim instanceof java.util.Collection) {
                        @SuppressWarnings("unchecked")
                        java.util.Collection<String> authList = (java.util.Collection<String>) authoritiesClaim;
                        for (String auth : authList) {
                            authorities.add(new SimpleGrantedAuthority(auth));
                        }
                    }
                }
                
                // 添加默认的SCOPE权限
                userRequest.getAccessToken().getScopes().forEach(scope -> 
                    authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope))
                );
                
                // 如果没有特定权限，至少添加用户角色
                if (authorities.isEmpty()) {
                    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                }
                
                return new DefaultOidcUser(authorities, idToken, userInfo, "preferred_username");
            }
        };
    }
}